package com.lujianfei.mqtt.net.config

import com.lujianfei.mqtt.login.mvvm.BaseResponse
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract

/**
 * @Author: wn
 * @Date: 2024/5/7 16:24
 * @Description: 通过 BaseResponse 中的 code 判断是否拿到数据
 */

/**
 * 接口成功且业务成功 code==SUCCESS 的情况
 * @receiver BaseResponse
 * @param block 传入 lambda 获取 code 与 message  data--T
 * @return BaseResponse
 */
@OptIn(ExperimentalContracts::class)
inline fun <reified T> BaseResponse<T>.onOK(block: (code: Int, data: T?, message: String?) -> Unit): BaseResponse<T> {
  contract {
    callsInPlace(block, InvocationKind.AT_MOST_ONCE)
  }
  if (code == BaseResponse.SERVER_CODE_SUCCESS)
    block(code, data, msg)
  return this
}

/**
 * 接口成功，但是业务返回code不是1或1001的情况
 * @receiver BaseResponse
 * @param block 传入 lambda 获取 code 与 message
 * @return BaseResponse
 */
@OptIn(ExperimentalContracts::class)
inline fun <T> BaseResponse<T>.onError(block: (code: Int, message: String?) -> Unit): BaseResponse<T> {
// 函数参数将被 最多调用一次
  contract {
    callsInPlace(block, InvocationKind.AT_MOST_ONCE)
  }
  // 同时不等于 1 和 1001
  if (code == BaseResponse.SERVER_CODE_FAILED) {
    block(code, msg ?: "Error Message Null")
  }
  return this
}
